#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <gtk/gtk.h>

#include "callbacks.h"
#include "interface.h"
#include "support.h"


void
on_button_clicked                      (GtkButton       *button,
                                        gpointer         user_data)
{
    enum {ADD = 1, MINUS, MULTIPLY, DIVIDE};
    static int sum = 0, reset = 0, operation = ADD, init = 1;
    static char str[1024];
    char key[10];

    strcpy (key, (char *)gtk_button_get_label((GtkButton *)button));
    switch (key[0]) {
           case '0':
           case '1':
           case '2':
           case '3':
           case '4':
           case '5':
           case '6':
           case '7':
           case '8':
           case '9':
                if (reset) {
                   str[0] = '\0';
                   reset = 0;
                }
                strcat (str, key);                                        
                gtk_entry_set_text ((GtkEntry *)entry1, str);
                break;
           case '+':
                sum += atoi (str);
                reset = 1;
                sprintf (str, "%d", sum);
                init = 0;
                operation = ADD;
                break;
           case '-':
                sum -= atoi (str);
                reset = 1;
                sprintf (str, "%d", sum);
                init = 0;
                operation = MINUS;
                break;
           case '*':
                if (init == 1) {
                   sum = 1;
                   init = 0;
                }
                sum *= atoi (str);
                reset = 1;
                sprintf (str, "%d", sum);
                init = 0;
                operation = MULTIPLY;
                break;
           case '/':
                if (init == 1) {
                   sum = atoi (str);
                   init = 0;
                } else {
                   sum /= atoi (str);
                }
                reset = 1;
                sprintf (str, "%d", sum);
                init = 0;
                operation = DIVIDE;
                break;
           case '=':
                switch (operation) {
                       case ADD:
                            sum += atoi (str);
                            break;
                       case MINUS:
                            sum -= atoi (str);
                            break;
                       case MULTIPLY:
                            sum *= atoi (str);
                            break;
                       case DIVIDE:
                            sum /= atoi (str);
                            break;
                }
                sprintf (str, "%d", sum);
                reset = 1;
                sum = 0;
                operation = ADD;
                init = 1;
                break;
    }
                
    gtk_entry_set_text ((GtkEntry *)entry1, str);
}

